import request from '@/utils/request'
import {genKeyPair} from '@/api/genKeyPair'
// pc端固定客户端授权id
const clientId = import.meta.env.VITE_APP_CLIENT_ID;
const encryptHeader = import.meta.env.VITE_APP_ENCRYPT_HEADER;

// 登录方法
export function login(tenantId, username, password, code, uuid) {
  const params = {
    tenantId,
    username,
    password,
    code,
    uuid,
    clientId: clientId,
    grantType: 'password'
  }

  return new Promise((resolve, reject) => {
    genKeyPair((uuid, public_key) => {
      request({
        url: '/auth/login',
        headers: {
          isToken: false,
          isEncrypt: false,
          [encryptHeader]: uuid,
          publicKey: public_key,
          repeatSubmit: false
        },
        method: 'post',
        data: params
      }).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  
    // resolve({
    //   data: {
    //     access_token: '1234567890',
    //     refresh_token: '0987654321',
    //     token_type: 'bearer',
    //     expires_in: 3600,
    //     name: 'admin',
    //     token: '1234567890',
    //     roles: ['admin'],
    //     permissions: ['admin', 'editor'],
    //     tenantId: '1',
    //     tenantName: '超级管理员',
    //     userInfo: {
    //       userId: '1',
    //       username: 'admin',
    //       nickname: '超级管理员',
    //     }
    //   },
    //   code: 200,
    //   message: '登录成功'
    // })
  });
}

// 注册方法
export function register(data) {
  return new Promise((resolve, reject) => {
    genKeyPair((uuid, public_key) => {
      request({
        url: '/auth/register',
        headers: {
          isToken: false,
          isEncrypt: true,
          [encryptHeader]: uuid,
          publicKey: public_key
        },
        method: 'post',
        data: params
      }).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  })

}

// 获取用户详细信息
export function getInfo() {
  // return request({
  //   url: '/system/user/getInfo',
  //   method: 'get'
  // })

  return new Promise((resolve, reject) => {
    resolve({
      data: {
        user: {
          userId: '1',
          username: 'admin',
          nickname: '超级管理员',
          url: 'URL_ADDRESS'  
        }
      }
    })
  })
}

// 退出方法
export function logout() {
  return request({
    url: '/auth/logout',
    method: 'post'
  })
}

// 获取验证码
export function getCodeImg() {
  return request({
    url: '/auth/code',
    headers: {
      isToken: false
    },
    method: 'get',
    timeout: 20000
  })
}

// 获取租户列表
export function getTenantList() {
  return request({
    url: '/auth/tenant/list',
    headers: {
      isToken: false
    },
    method: 'get'
  });
}
